/**
 * @ClassName: Algorithm-and-Data-Structure
 * @Description: 冒泡排序及优化
 * @Author: zhouhong
 * @Create: 2021-04-09 12:38
 **/

public class BubbleSort {

    private BubbleSort(){}

    public static void sort(int[] data){
        for (int i = 0; i < data.length - 1; i++) {
            // arr[n - i, n)已经排好序
            // 通过冒泡在 arr[n - i - 1] 位置放上合适的元素
            for (int j = 0; j < data.length - i - 1 ; j++) {
                if (data[j] > data[j + 1]){
                    swap(data, j, j + 1);
                }
            }
        }
    }

    public static void sort2(int[] data){
        for (int i = 0; i < data.length - 1; i++) {
            // arr[n - i, n)已经排好序
            // 通过冒泡在 arr[n - i - 1] 位置放上合适的元素
            boolean isSwapped = false;
            for (int j = 0; j < data.length - i - 1 ; j++) {
                if (data[j] > data[j + 1]){
                    swap(data, j, j + 1);
                    isSwapped = true;
                }
            }
            if (!isSwapped){
                break;
            }
        }
    }
    private static void swap(int[] data, int i, int j){
        int temp = data[i];
        data[i] = data[j];
        data[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {2,4,32,10,92,12,3,43,5545,653,44,34,43};
        sort2(arr);
        for (int a: arr) {
            System.out.println(a);
        }
    }
}
